<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="修改规则配置"
    @visible-change="handleVisibleChange"
    @ok="handleOK"
  >
    <div class="pt-3px pr-3px">
      <BasicForm @register="registerForm" :model="model" />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, nextTick } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { schemas } from '/@/views/rule/edit/schema';
  import { Rule } from '/@/api/monitor/entity/entity';
  import { editRule } from '/@/api/monitor/rule';

  export default defineComponent({
    components: { BasicModal, BasicForm },
    props: {
      userData: { type: Object },
    },
    emits: ['exitEditRule', 'register'],
    setup(props, { emit }) {
      let tempID = -1;
      const modelRef = ref({});
      const [registerForm, getFormProps] = useForm({
        labelWidth: 120,
        size: 'large',
        schemas,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 24,
        },
      });

      const [register, { setModalProps, closeModal }] = useModalInner((data) => {
        data && onDataReceive(data);
      });

      function onDataReceive(data) {
        tempID = data.rl.id;
        modelRef.value = data.rl;
        setModalProps({ title: '规则ID-' + data.rl.id });
      }

      async function handleOK() {
        let rl: Rule = getFormProps.getFieldsValue();
        rl.id = tempID;
        rl.min_alarm = Number(rl.min_alarm);
        rl.max_alarm = Number(rl.max_alarm);
        closeModal();
        emit('exitEditRule', await editRule(rl));
      }

      function handleVisibleChange(v) {
        v && props.userData && nextTick(() => onDataReceive(props.userData));
      }

      return {
        register,
        schemas,
        registerForm,
        model: modelRef,
        handleVisibleChange,
        setModalProps,
        handleOK,
        getFormProps,
      };
    },
  });
</script>
